<?php
/**
 * Created by PhpStorm.
 * User: lelouchms
 * Date: 2019/3/28
 * Time: 16:08
 */

namespace app\backend\controller\admin\v1;

use app\common\exception\CustomerException;
use app\common\exception\ValidateException;

class UserAppointment extends Base
{

    public function initialize()
    {
        parent::initialize();
        $this->model = new \app\common\model\UserAppointment();
    }

    public function getStatusList()
    {
        return $this->model->getStatusList();
    }

    public function index()
    {
        list($where, $sort, $order, $offset, $limit, $infinite) = $this->buildParams();
        $count = $this->model->with(["house", "user"])->where($where)->order($sort, $order)->count();
        $query = $this->model
            ->allowField(true)
            ->where($where)
            ->with(["house", "user"])
            ->order($sort, $order);
        if ($infinite !== true) {
            $query->limit($offset, $limit);
        }
        if (!empty($this->expectFields)) $query->field($this->dataTablePrefix($this->expectFields), true);
        $list = $query->select();
        $returnData = [
            "count" => $count,
            "list" => $list
        ];
        $data = $returnData['list'];

        foreach ($data as $key => $value) {
            $data[$key] = $this->model->selectById($value['id'], true);
        }
        $returnData['list'] = $data;
        return $returnData;
    }

    public function update()
    {
        $requestData = $this->request->only(['user_id', 'username', 'phone', 'house_id', 'time', 'remark', 'status', 'id', 'seller_id', 'is_complete']);
        if (empty($requestData['seller_id']) && $requestData['status'] == 2) throw new CustomerException("请选择销售员");
        $validate = new \app\common\validate\UserAppointment();
        $flag = $validate->scene("update")->check($requestData);
        if ($flag === false) {
            throw new ValidateException($validate->getError());
        }
        //  如果状态改为已处理,且有销售id则插入到销售带看表中
        if (!empty($requestData['seller_id']) && $requestData['status'] == 2 && $requestData['is_complete'] == 1) {
            $house = model("house")->get($requestData['house_id']);
            model("SellerAppointment")->insert([
                'user_id' => $requestData['seller_id'],
                'username' => $requestData['username'],
                'phone' => $requestData['phone'],
                'status' => 1,
                'amount' => $house['amount'],
                'house_id' => $requestData['house_id']
            ]);
            $requestData['is_complete'] = 2;
        }
        $count = $this->model->allowField(true)->save($requestData, ['id' => $requestData['id']]);
        if ($count > 1) throw new CustomerException("编辑失败");
        $this->_removeCache($requestData);
    }

    public function findById($id)
    {
        return $this->model->selectById($id, true);
    }
}